import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useTabsStore = defineStore('tabs', () => {
  const tabs = ref([
    {
      name: 'dashboard',
      title: '仪表盘',
      path: '/admin/dashboard',
      closable: false
    }
  ])
  
  const activeTab = ref('dashboard')
  
  // 添加标签页
  const addTab = (tab) => {
    const existingTab = tabs.value.find(t => t.name === tab.name)
    if (!existingTab) {
      tabs.value.push({
        ...tab,
        closable: true
      })
    }
    activeTab.value = tab.name
  }
  
  // 关闭标签页
  const removeTab = (tabName) => {
    const index = tabs.value.findIndex(t => t.name === tabName)
    if (index > -1 && tabs.value[index].closable) {
      tabs.value.splice(index, 1)
      
      // 如果关闭的是当前激活的标签页，切换到前一个标签页
      if (activeTab.value === tabName) {
        const newIndex = index > 0 ? index - 1 : 0
        activeTab.value = tabs.value[newIndex]?.name || 'dashboard'
      }
    }
  }
  
  // 设置激活标签页
  const setActiveTab = (tabName) => {
    activeTab.value = tabName
  }
  
  // 关闭其他标签页
  const closeOtherTabs = (tabName) => {
    tabs.value = tabs.value.filter(t => !t.closable || t.name === tabName)
    activeTab.value = tabName
  }
  
  // 关闭所有标签页
  const closeAllTabs = () => {
    tabs.value = tabs.value.filter(t => !t.closable)
    activeTab.value = 'dashboard'
  }
  
  return {
    tabs,
    activeTab,
    addTab,
    removeTab,
    setActiveTab,
    closeOtherTabs,
    closeAllTabs
  }
})